package com.wyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyy.beans.Driver;
import com.wyy.dao.DriverDao;
import com.wyy.service.DriverService;
import com.wyy.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DriverServiceImpl implements DriverService {

    @Autowired
    private DriverDao driverDao;

    @Override
    public Result<Driver> addDriver(Driver driver) {
        QueryWrapper<Driver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "telephone_number", driver.getTelephoneNumber());
        Driver newDriver = driverDao.selectOne(queryWrapper);
        if (newDriver != null) {
            return new Result<>(Result.ResultStatus.Failed.code, "重复");
        }

        int aff = driverDao.insert(driver);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Driver> deleteDriver(long id) {
        int aff = driverDao.deleteById(id);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Driver> updateDriver(Driver driver) {
        QueryWrapper<Driver> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "username", driver.getUsername());
        Driver newDriver = driverDao.selectOne(queryWrapper);
        if (newDriver == null) {
            return new Result<>(Result.ResultStatus.Failed.code, "重复");
        }

        driver.setId(newDriver.getId());
        int aff = driverDao.updateById(driver);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Driver> getDriver(long id) {
        Driver driver = driverDao.selectById(id);
        return driver == null ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success", driver);
    }

    @Override
    public Result<List<Driver>> getDrivers() {
        List<Driver> drivers = driverDao.findAllDrivers();
        return drivers.size() == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success", drivers);
    }
}
